<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Eigen: Common pitfalls</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
  $(document).ready(function() { init_search(); });
/* @license-end */
</script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
</script>
<script type="text/javascript" async="async" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="eigendoxy.css" rel="stylesheet" type="text/css">
<!--  -->
<script type="text/javascript" src="eigen_navtree_hacks.js"></script>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="Eigen_Silly_Professor_64x64.png"/></td>
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname"><a href="http://eigen.tuxfamily.org">Eigen</a>
   &#160;<span id="projectnumber">3.4.90 (git rev 67eeba6e720c5745abc77ae6c92ce0a44aa7b7ae)</span>
   </div>
  </td>
   <td>        <div id="MSearchBox" class="MSearchBoxInactive">
        <span class="left">
          <img id="MSearchSelect" src="search/mag_sel.svg"
               onmouseover="return searchBox.OnSearchSelectShow()"
               onmouseout="return searchBox.OnSearchSelectHide()"
               alt=""/>
          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)" 
               onblur="searchBox.OnSearchFieldFocus(false)" 
               onkeyup="searchBox.OnSearchFieldChange(event)"/>
          </span><span class="right">
            <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.svg" alt=""/></a>
          </span>
        </div>
</td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
      <div id="nav-sync" class="sync"></div>
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('TopicPitfalls.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="PageDoc"><div class="header">
  <div class="headertitle">
<div class="title">Common pitfalls </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><h1><a class="anchor" id="TopicPitfalls_template_keyword"></a>
Compilation error with template methods</h1>
<p>See this <a class="el" href="TopicTemplateKeyword.html">page </a>.</p>
<h1><a class="anchor" id="TopicPitfalls_aliasing"></a>
Aliasing</h1>
<p>Don't miss this <a class="el" href="group__TopicAliasing.html">page </a> on aliasing, especially if you got wrong results in statements where the destination appears on the right hand side of the expression.</p>
<h1><a class="anchor" id="TopicPitfalls_alignment_issue"></a>
Alignment Issues (runtime assertion)</h1>
<p>Eigen does explicit vectorization, and while that is appreciated by many users, that also leads to some issues in special situations where data alignment is compromised. Indeed, prior to C++17, C++ does not have quite good enough support for explicit data alignment. In that case your program hits an assertion failure (that is, a "controlled crash") with a message that tells you to consult this page: </p><div class="fragment"><div class="line">http:<span class="comment">//eigen.tuxfamily.org/dox/group__TopicUnalignedArrayAssert.html</span></div>
</div><!-- fragment --><p> Have a look at <a class="el" href="group__TopicUnalignedArrayAssert.html">it </a> and see for yourself if that's something that you can cope with. It contains detailed information about how to deal with each known cause for that issue.</p>
<p>Now what if you don't care about vectorization and so don't want to be annoyed with these alignment issues? Then read <a class="el" href="group__TopicUnalignedArrayAssert.html#getrid">how to get rid of them </a>.</p>
<h1><a class="anchor" id="TopicPitfalls_auto_keyword"></a>
C++11 and the auto keyword</h1>
<p>In short: do not use the auto keywords with Eigen's expressions, unless you are 100% sure about what you are doing. In particular, do not use the auto keyword as a replacement for a <code>Matrix&lt;&gt;</code> type. Here is an example:</p>
<div class="fragment"><div class="line"><a class="code" href="group__matrixtypedefs.html#ga99b41a69f0bf64eadb63a97f357ab412">MatrixXd</a> A, B;</div>
<div class="line"><span class="keyword">auto</span> C = A*B;</div>
<div class="line"><span class="keywordflow">for</span>(...) { ... w = C * v;  ...}</div>
<div class="ttc" id="agroup__matrixtypedefs_html_ga99b41a69f0bf64eadb63a97f357ab412"><div class="ttname"><a href="group__matrixtypedefs.html#ga99b41a69f0bf64eadb63a97f357ab412">Eigen::MatrixXd</a></div><div class="ttdeci">Matrix&lt; double, Dynamic, Dynamic &gt; MatrixXd</div><div class="ttdoc">Dynamic×Dynamic matrix of type double.</div><div class="ttdef"><b>Definition:</b> Matrix.h:501</div></div>
</div><!-- fragment --><p>In this example, the type of C is not a <code>MatrixXd</code> but an abstract expression representing a matrix product and storing references to <code>A</code> and <code>B</code>. Therefore, the product of <code>A*B</code> will be carried out multiple times, once per iteration of the for loop. Moreover, if the coefficients of <code>A</code> or <code>B</code> change during the iteration, then <code>C</code> will evaluate to different values as in the following example:</p>
<div class="fragment"><div class="line"><a class="code" href="group__matrixtypedefs.html#ga99b41a69f0bf64eadb63a97f357ab412">MatrixXd</a> A = ..., B = ...;</div>
<div class="line"><span class="keyword">auto</span> C = A*B;</div>
<div class="line"><a class="code" href="group__matrixtypedefs.html#ga99b41a69f0bf64eadb63a97f357ab412">MatrixXd</a> R1 = C;</div>
<div class="line">A = ...;</div>
<div class="line"><a class="code" href="group__matrixtypedefs.html#ga99b41a69f0bf64eadb63a97f357ab412">MatrixXd</a> R2 = C;</div>
</div><!-- fragment --><p> for which we end up with <code>R1</code> &ne; <code>R2</code>.</p>
<p>Here is another example leading to a segfault: </p><div class="fragment"><div class="line"><span class="keyword">auto</span> C = ((A+B).eval()).transpose();</div>
<div class="line"><span class="comment">// do something with C</span></div>
</div><!-- fragment --><p> The problem is that <code>eval()</code> returns a temporary object (in this case a <code>MatrixXd</code>) which is then referenced by the <code>Transpose&lt;&gt;</code> expression. However, this temporary is deleted right after the first line, and then the <code>C</code> expression references a dead object. One possible fix consists in applying <code>eval()</code> on the whole expression: </p><div class="fragment"><div class="line"><span class="keyword">auto</span> C = (A+B).transpose().eval();</div>
</div><!-- fragment --><p>The same issue might occur when sub expressions are automatically evaluated by Eigen as in the following example: </p><div class="fragment"><div class="line"><a class="code" href="group__matrixtypedefs.html#ga8554c6170729f01c7572574837ecf618">VectorXd</a> u, v;</div>
<div class="line"><span class="keyword">auto</span> C = u + (A*v).normalized();</div>
<div class="line"><span class="comment">// do something with C</span></div>
<div class="ttc" id="agroup__matrixtypedefs_html_ga8554c6170729f01c7572574837ecf618"><div class="ttname"><a href="group__matrixtypedefs.html#ga8554c6170729f01c7572574837ecf618">Eigen::VectorXd</a></div><div class="ttdeci">Matrix&lt; double, Dynamic, 1 &gt; VectorXd</div><div class="ttdoc">Dynamic×1 vector of type double.</div><div class="ttdef"><b>Definition:</b> Matrix.h:501</div></div>
</div><!-- fragment --><p> Here the <code>normalized()</code> method has to evaluate the expensive product <code>A*v</code> to avoid evaluating it twice. Again, one possible fix is to call <code></code>.eval() on the whole expression: </p><div class="fragment"><div class="line"><span class="keyword">auto</span> C = (u + (A*v).normalized()).eval();</div>
</div><!-- fragment --><p> In this case, <code>C</code> will be a regular <code>VectorXd</code> object. Note that <a class="el" href="classEigen_1_1DenseBase.html#aa73e57a2f0f7cfcb4ad4d55ea0b6414b">DenseBase::eval()</a> is smart enough to avoid copies when the underlying expression is already a plain <code>Matrix&lt;&gt;</code>.</p>
<h1><a class="anchor" id="TopicPitfalls_header_issues"></a>
Header Issues (failure to compile)</h1>
<p>With all libraries, one must check the documentation for which header to include. The same is true with Eigen, but slightly worse: with Eigen, a method in a class may require an additional <code>#include</code> over what the class itself requires! For example, if you want to use the <code>cross()</code> method on a vector (it computes a cross-product) then you need to: </p><div class="fragment"><div class="line"><span class="preprocessor">#include&lt;Eigen/Geometry&gt;</span></div>
</div><!-- fragment --><p> We try to always document this, but do tell us if we forgot an occurrence.</p>
<h1><a class="anchor" id="TopicPitfalls_ternary_operator"></a>
Ternary operator</h1>
<p>In short: avoid the use of the ternary operator <code>(COND ? THEN : ELSE)</code> with Eigen's expressions for the <code>THEN</code> and <code>ELSE</code> statements. To see why, let's consider the following example: </p><div class="fragment"><div class="line"><a class="code" href="group__matrixtypedefs.html#ga5ec9ce2d8adbcd6888f3fbf2e1c095a4">Vector3f</a> A;</div>
<div class="line">A &lt;&lt; 1, 2, 3;</div>
<div class="line"><a class="code" href="group__matrixtypedefs.html#ga5ec9ce2d8adbcd6888f3fbf2e1c095a4">Vector3f</a> B = ((1 &lt; 0) ? (A.reverse()) : A);</div>
<div class="ttc" id="agroup__matrixtypedefs_html_ga5ec9ce2d8adbcd6888f3fbf2e1c095a4"><div class="ttname"><a href="group__matrixtypedefs.html#ga5ec9ce2d8adbcd6888f3fbf2e1c095a4">Eigen::Vector3f</a></div><div class="ttdeci">Matrix&lt; float, 3, 1 &gt; Vector3f</div><div class="ttdoc">3×1 vector of type float.</div><div class="ttdef"><b>Definition:</b> Matrix.h:500</div></div>
</div><!-- fragment --><p> This example will return <code>B = 3, 2, 1</code>. Do you see why? The reason is that in c++ the type of the <code>ELSE</code> statement is inferred from the type of the <code>THEN</code> expression such that both match. Since <code>THEN</code> is a <code>Reverse&lt;Vector3f&gt;</code>, the <code>ELSE</code> statement A is converted to a <code>Reverse&lt;Vector3f&gt;</code>, and the compiler thus generates: </p><div class="fragment"><div class="line"><a class="code" href="group__matrixtypedefs.html#ga5ec9ce2d8adbcd6888f3fbf2e1c095a4">Vector3f</a> B = ((1 &lt; 0) ? (A.reverse()) : Reverse&lt;Vector3f&gt;(A));</div>
</div><!-- fragment --><p> In this very particular case, a workaround would be to call A.reverse().eval() for the <code>THEN</code> statement, but the safest and fastest is really to avoid this ternary operator with Eigen's expressions and use a if/else construct.</p>
<h1><a class="anchor" id="TopicPitfalls_pass_by_value"></a>
Pass-by-value</h1>
<p>If you don't know why passing-by-value is wrong with Eigen, read this <a class="el" href="group__TopicPassingByValue.html">page </a> first.</p>
<p>While you may be extremely careful and use care to make sure that all of your code that explicitly uses Eigen types is pass-by-reference you have to watch out for templates which define the argument types at compile time.</p>
<p>If a template has a function that takes arguments pass-by-value, and the relevant template parameter ends up being an Eigen type, then you will of course have the same alignment problems that you would in an explicitly defined function passing Eigen types by reference.</p>
<p>Using Eigen types with other third party libraries or even the STL can present the same problem. <code>boost::bind</code> for example uses pass-by-value to store arguments in the returned functor. This will of course be a problem.</p>
<p>There are at least two ways around this:</p><ul>
<li>If the value you are passing is guaranteed to be around for the life of the functor, you can use boost::ref() to wrap the value as you pass it to boost::bind. Generally this is not a solution for values on the stack as if the functor ever gets passed to a lower or independent scope, the object may be gone by the time it's attempted to be used.</li>
<li>The other option is to make your functions take a reference counted pointer like boost::shared_ptr as the argument. This avoids needing to worry about managing the lifetime of the object being passed.</li>
</ul>
<h1><a class="anchor" id="TopicPitfalls_matrix_bool"></a>
Matrices with boolean coefficients</h1>
<p>The current behaviour of using <code><a class="el" href="classEigen_1_1Matrix.html" title="The matrix class, also used for vectors and row-vectors.">Matrix</a></code> with boolean coefficients is inconsistent and likely to change in future versions of <a class="el" href="namespaceEigen.html" title="Namespace containing all symbols from the Eigen library.">Eigen</a>, so please use it carefully!</p>
<p>A simple example for such an inconsistency is</p>
<div class="fragment"><div class="line"><span class="keyword">template</span>&lt;<span class="keywordtype">int</span> Size&gt;</div>
<div class="line"><span class="keywordtype">void</span> foo() {</div>
<div class="line">  <a class="code" href="classEigen_1_1Matrix.html">Eigen::Matrix&lt;bool, Size, Size&gt;</a> A, B, C;</div>
<div class="line">  A.<a class="code" href="classEigen_1_1PlainObjectBase.html#a8700dc6d8e05436c0b34ae15ca9274a5">setOnes</a>();</div>
<div class="line">  B.<a class="code" href="classEigen_1_1PlainObjectBase.html#a8700dc6d8e05436c0b34ae15ca9274a5">setOnes</a>();</div>
<div class="line"> </div>
<div class="line">  C = A * B - A * B;</div>
<div class="line">  std::cout &lt;&lt; C &lt;&lt; <span class="stringliteral">&quot;\n&quot;</span>;</div>
<div class="line">}</div>
<div class="ttc" id="aclassEigen_1_1Matrix_html"><div class="ttname"><a href="classEigen_1_1Matrix.html">Eigen::Matrix</a></div><div class="ttdoc">The matrix class, also used for vectors and row-vectors.</div><div class="ttdef"><b>Definition:</b> Matrix.h:182</div></div>
<div class="ttc" id="aclassEigen_1_1PlainObjectBase_html_a8700dc6d8e05436c0b34ae15ca9274a5"><div class="ttname"><a href="classEigen_1_1PlainObjectBase.html#a8700dc6d8e05436c0b34ae15ca9274a5">Eigen::PlainObjectBase::setOnes</a></div><div class="ttdeci">Derived &amp; setOnes(Index size)</div><div class="ttdef"><b>Definition:</b> CwiseNullaryOp.h:716</div></div>
</div><!-- fragment --><p>since calling <code>foo&lt;3&gt;()</code> prints the zero matrix while calling <code>foo&lt;10&gt;()</code> prints the identity matrix. </p>
</div></div><!-- contents -->
</div><!-- PageDoc -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
  <ul>
    <li class="footer">Generated on Thu Apr 21 2022 13:07:55 for Eigen by
    <a href="http://www.doxygen.org/index.html">
    <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.9.1 </li>
  </ul>
</div>
</body>
</html>
